using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Tryit.Models;
using Tryit.Services;
using Tryit.Views;

namespace Tryit.ViewModels
{
    public class MaterialManagementViewModel : BindableBase
    {
        private readonly MaterialService _materialService;
        private readonly Window _window;
        private ObservableCollection<Material> _materials;
        private Material _selectedMaterial;

        public ObservableCollection<Material> Materials
        {
            get => _materials;
            set => SetProperty(ref _materials, value);
        }

        public Material SelectedMaterial
        {
            get => _selectedMaterial;
            set => SetProperty(ref _selectedMaterial, value);
        }

        private DelegateCommand _addMaterialCommand;
        public DelegateCommand AddMaterialCommand => _addMaterialCommand ??= new DelegateCommand(ExecuteAddMaterial);

        private DelegateCommand<Material> _editMaterialCommand;
        public DelegateCommand<Material> EditMaterialCommand => _editMaterialCommand ??= new DelegateCommand<Material>(ExecuteEditMaterial);

        private DelegateCommand<Material> _deleteMaterialCommand;
        public DelegateCommand<Material> DeleteMaterialCommand => _deleteMaterialCommand ??= new DelegateCommand<Material>(ExecuteDeleteMaterial);

        private DelegateCommand<Material> _copyMaterialCommand;
        public DelegateCommand<Material> CopyMaterialCommand => _copyMaterialCommand ??= new DelegateCommand<Material>(ExecuteCopyMaterial);

        private DelegateCommand _refreshMaterialsCommand;
        public DelegateCommand RefreshMaterialsCommand => _refreshMaterialsCommand ??= new DelegateCommand(ExecuteRefreshMaterials);

        private DelegateCommand _closeCommand;
        public DelegateCommand CloseCommand => _closeCommand ??= new DelegateCommand(ExecuteClose);

        public MaterialManagementViewModel(Window window)
        {
            _materialService = new MaterialService();
            _window = window;
            _materials = new ObservableCollection<Material>();
            LoadMaterials();
        }

        private void LoadMaterials()
        {
            try
            {
                var materialNames = _materialService.GetAllMaterialNames();
                Materials.Clear();
                foreach (var name in materialNames)
                {
                    var material = _materialService.LoadMaterial(name);
                    if (material != null)
                    {
                        Materials.Add(material);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载材料列表失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ExecuteAddMaterial()
        {
            try
            {
                var material = new Material("新材料", "材料描述");
                var dialog = new MaterialEditDialog(material);
                dialog.Owner = _window;
                
                if (dialog.ShowDialog() == true)
                {
                    await _materialService.SaveMaterialAsync(material);
                    Materials.Add(material);
                    SelectedMaterial = material;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加材料失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ExecuteEditMaterial(Material material)
        {
            if (material == null) return;

            try
            {
                var dialog = new MaterialEditDialog(material);
                dialog.Owner = _window;
                
                if (dialog.ShowDialog() == true)
                {
                    await _materialService.SaveMaterialAsync(material);
                    // 刷新显示
                    var index = Materials.IndexOf(material);
                    if (index >= 0)
                    {
                        Materials[index] = material;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"编辑材料失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ExecuteDeleteMaterial(Material material)
        {
            if (material == null) return;

            var result = MessageBox.Show($"确定要删除材料 '{material.Name}' 吗？", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    await _materialService.DeleteMaterialAsync(material.Name);
                    Materials.Remove(material);
                    if (SelectedMaterial == material)
                    {
                        SelectedMaterial = Materials.FirstOrDefault();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除材料失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private async void ExecuteCopyMaterial(Material material)
        {
            if (material == null) return;

            try
            {
                var newName = $"{material.Name}_副本";
                var counter = 1;
                while (_materialService.MaterialExists(newName))
                {
                    newName = $"{material.Name}_副本_{counter}";
                    counter++;
                }

                var newMaterial = await _materialService.CopyMaterialAsync(material.Name, newName);
                Materials.Add(newMaterial);
                SelectedMaterial = newMaterial;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制材料失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecuteRefreshMaterials()
        {
            LoadMaterials();
        }

        private void ExecuteClose()
        {
            _window.Close();
        }
    }
} 